package com.thoughtful.registry.zk;

import java.net.InetSocketAddress;
import java.util.List;

import com.thoughtful.loadbalance.LoadBalance;
import com.thoughtful.registry.ServiceDiscovery;
import com.thoughtful.registry.zk.util.CuratorUtils;
import com.thoughtful.remoting.dto.RpcRequest;
import com.thougtful.enums.RpcErrorMessageEnum;
import com.thougtful.exception.RpcException;
import com.thougtful.extension.ExtensionLoader;
import com.thougtful.utils.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

/**
 * @author yushun
 * @createTime 2022/10/19 - 16:09
 **/
@Slf4j
public class ZkServiceDiscoveryImpl implements ServiceDiscovery {

    private LoadBalance loadBalance;

    public ZkServiceDiscoveryImpl() {
        loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("loadBalance");
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {
        String rpcServiceName = rpcRequest.getRpcServiceName();
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
        if(CollectionUtil.isEmpty(serviceUrlList)) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_NOT_FOUNT, rpcServiceName);
        }
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList, rpcRequest);
        log.info("Successfully found the service address: [{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        return new InetSocketAddress(socketAddressArray[0], Integer.parseInt(socketAddressArray[1]));
    }
}
